<!--
 * @Author: Craft
 * @Date: 2024-08-18
 * @Description: 暗黑破坏神2重置版BD详情页
-->
<template>
  <view class="d2r-container">
    <view v-if="loading" class="d2r-loading">
      <u-loading-icon mode="circle" color="#d4af37"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
    
    <view v-else-if="!build" class="d2r-empty">
      <u-icon name="info-circle" size="48" color="#a0a0a0"></u-icon>
      <text class="empty-text">未找到BD信息</text>
    </view>
    
    <view v-else class="build-detail">
      <!-- BD头部 -->
      <view class="build-header">
        <view class="build-title-section">
          <text class="build-title">{{ build.title }}</text>
          <view class="class-tag" :class="getClassTagClass(build.class)">{{ build.class }}</view>
        </view>
        
        <view class="build-meta">
          <view class="meta-item">
            <text class="meta-label">作者:</text>
            <text class="meta-value">{{ build.author }}</text>
          </view>
          <view class="meta-item">
            <text class="meta-label">发布日期:</text>
            <text class="meta-value">{{ formatDate(build.createDate) }}</text>
          </view>
          <view class="meta-stats">
            <view class="stat-item">
              <u-icon name="eye" size="14" color="#a0a0a0"></u-icon>
              <text class="stat-text">{{ build.viewCount }}</text>
            </view>
            <view class="stat-item">
              <u-icon name="star" size="14" color="#a0a0a0"></u-icon>
              <text class="stat-text">{{ build.favCount }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- BD内容 -->
      <view class="build-content-card">
        <text class="card-title">BD详情</text>
        <text class="build-content">{{ build.content }}</text>
      </view>
      
      <!-- 核心装备 -->
      <view class="build-items-card" v-if="buildItems.length > 0">
        <text class="card-title">核心装备</text>
        <view class="items-list">
          <view 
            class="item-card" 
            v-for="item in buildItems" 
            :key="item._id"
            @click="navigateToItemDetail(item._id)"
          >
            <view class="item-image-container" :class="'quality-border ' + getQualityClass(item.quality)">
              <image class="item-image" :src="item.image || '/static/items/default.png'" mode="aspectFit"></image>
            </view>
            <view class="item-info">
              <text class="item-name" :class="getQualityTextClass(item.quality)">{{ item.name }}</text>
              <text class="item-type">{{ item.type }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 相关BD -->
      <view class="related-builds-card" v-if="relatedBuilds.length > 0">
        <text class="card-title">相关BD</text>
        <view class="related-list">
          <view 
            class="related-item" 
            v-for="relatedBuild in relatedBuilds" 
            :key="relatedBuild._id"
            @click="navigateToBuildDetail(relatedBuild._id)"
          >
            <view class="related-header">
              <text class="related-title">{{ relatedBuild.title }}</text>
              <view class="class-tag" :class="getClassTagClass(relatedBuild.class)">{{ relatedBuild.class }}</view>
            </view>
            <view class="related-author">
              <text>{{ relatedBuild.author }}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <view class="action-button" @click="toggleFavorite">
          <u-icon :name="isFavorite ? 'star-fill' : 'star'" size="20" :color="isFavorite ? '#d4af37' : '#a0a0a0'"></u-icon>
          <text>{{ isFavorite ? '已收藏' : '收藏' }}</text>
        </view>
        <view class="action-button" @click="shareBuild">
          <u-icon name="share" size="20" color="#a0a0a0"></u-icon>
          <text>分享</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { loadData, updateFavorite } from '@/common/d2r-data'

// 数据
const build = ref(null)
const buildItems = ref([])
const relatedBuilds = ref([])
const loading = ref(true)
const isFavorite = ref(false)

// 获取页面参数
const buildId = ref('')

// 生命周期
onMounted(async () => {
  // 获取路由参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.$page?.options || {}
  
  if (options.id) {
    buildId.value = options.id
    await Promise.all([
      loadBuildData(),
      incrementViewCount()
    ])
  } else {
    loading.value = false
    uni.showToast({
      title: '缺少BD ID参数',
      icon: 'none'
    })
  }
  
  // 检查是否已收藏
  checkFavoriteStatus()
})

// 加载BD数据
async function loadBuildData() {
  try {
    loading.value = true
    
    // 查询单个BD
    const builds = await loadData('builds')
    build.value = builds.find(b => b._id === buildId.value)
    
    if (build.value) {
      // 加载BD中的装备
      await loadBuildItems()
      
      // 加载相关BD
      await loadRelatedBuilds()
    } else {
      uni.showToast({
        title: '未找到BD信息',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载BD数据失败', error)
    uni.showToast({
      title: '加载BD数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载BD中的装备
async function loadBuildItems() {
  if (!build.value || !build.value.items || build.value.items.length === 0) {
    return
  }
  
  try {
    const items = await loadData('items')
    buildItems.value = items.filter(item => build.value.items.includes(item._id))
  } catch (error) {
    console.error('加载装备数据失败', error)
  }
}

// 加载相关BD
async function loadRelatedBuilds() {
  if (!build.value) return
  
  try {
    const builds = await loadData('builds')
    relatedBuilds.value = builds.filter(b => 
      b._id !== buildId.value && b.class === build.value.class
    ).slice(0, 3) // 最多显示3个相关BD
  } catch (error) {
    console.error('加载相关BD失败', error)
  }
}

// 增加浏览次数
async function incrementViewCount() {
  // 在实际应用中，这里应该调用云函数或API来增加浏览次数
  // 这里仅做模拟
  try {
    const viewedBuilds = uni.getStorageSync('viewed_builds') || []
    
    // 如果没有浏览过，才增加浏览次数
    if (!viewedBuilds.includes(buildId.value)) {
      viewedBuilds.push(buildId.value)
      uni.setStorageSync('viewed_builds', viewedBuilds)
      
      // 这里应该调用API更新浏览次数
      console.log('增加浏览次数:', buildId.value)
    }
  } catch (e) {
    console.error('更新浏览次数失败', e)
  }
}

// 检查收藏状态
function checkFavoriteStatus() {
  try {
    const favoriteBuilds = uni.getStorageSync('favorite_builds') || []
    isFavorite.value = favoriteBuilds.includes(buildId.value)
  } catch (e) {
    console.error('获取收藏状态失败', e)
  }
}

// 切换收藏状态
async function toggleFavorite() {
  try {
    const favoriteBuilds = uni.getStorageSync('favorite_builds') || []
    
    if (isFavorite.value) {
      // 取消收藏
      const index = favoriteBuilds.indexOf(buildId.value)
      if (index !== -1) {
        favoriteBuilds.splice(index, 1)
      }
      await updateFavorite('builds', buildId.value, false)
      uni.showToast({
        title: '已取消收藏',
        icon: 'none'
      })
    } else {
      // 添加收藏
      favoriteBuilds.push(buildId.value)
      await updateFavorite('builds', buildId.value, true)
      uni.showToast({
        title: '收藏成功',
        icon: 'none'
      })
    }
    
    // 更新本地存储
    uni.setStorageSync('favorite_builds', favoriteBuilds)
    
    // 更新状态
    isFavorite.value = !isFavorite.value
  } catch (e) {
    console.error('更新收藏状态失败', e)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

// 分享BD
function shareBuild() {
  if (!build.value) return
  
  uni.showModal({
    title: '分享提示',
    content: '该功能将在后续版本中开放，敬请期待！',
    showCancel: false,
    confirmText: '我知道了'
  })
}

// 跳转到装备详情
function navigateToItemDetail(itemId) {
  uni.navigateTo({
    url: `/pages-sub/database/item-detail?id=${itemId}`
  })
}

// 跳转到BD详情
function navigateToBuildDetail(buildId) {
  uni.navigateTo({
    url: `/pages-sub/builds/build-detail?id=${buildId}`
  })
}

// 格式化日期
function formatDate(dateStr) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 获取品质样式类
function getQualityClass(quality) {
  switch (quality?.toLowerCase()) {
    case '普通': return 'normal'
    case '魔法': return 'magic'
    case '稀有': return 'rare'
    case '套装': return 'set'
    case '暗金': return 'unique'
    case '工艺': return 'crafted'
    default: return ''
  }
}

// 获取品质文本样式类
function getQualityTextClass(quality) {
  switch (quality?.toLowerCase()) {
    case '普通': return 'text-normal'
    case '魔法': return 'text-magic'
    case '稀有': return 'text-rare'
    case '套装': return 'text-set'
    case '暗金': return 'text-unique'
    case '工艺': return 'text-crafted'
    default: return ''
  }
}

// 获取职业标签样式类
function getClassTagClass(className) {
  switch (className) {
    case '亚马逊': return 'amazon'
    case '野蛮人': return 'barbarian'
    case '死灵法师': return 'necromancer'
    case '圣骑士': return 'paladin'
    case '法师': return 'sorceress'
    case '德鲁伊': return 'druid'
    case '刺客': return 'assassin'
    default: return ''
  }
}
</script>

<style lang="scss" scoped>
@import '@/common/d2r-theme.scss';
.d2r-container {
  min-height: 100vh;
  padding-bottom: 30px;
}

// BD详情
.build-detail {
  padding: 15px;
  
  // BD头部
  .build-header {
    background-color: $d2r-bg-darker;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .build-title-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      .build-title {
        font-size: 18px;
        color: $d2r-gold;
        font-weight: bold;
      }
    }
    
    .build-meta {
      .meta-item {
        display: flex;
        margin-bottom: 5px;
        
        .meta-label {
          width: 70px;
          font-size: 14px;
          color: $d2r-text-muted;
        }
        
        .meta-value {
          flex: 1;
          font-size: 14px;
          color: $d2r-text;
        }
      }
      
      .meta-stats {
        display: flex;
        margin-top: 10px;
        
        .stat-item {
          display: flex;
          align-items: center;
          margin-right: 15px;
          
          .stat-text {
            font-size: 14px;
            color: $d2r-text-muted;
            margin-left: 4px;
          }
        }
      }
    }
  }
  
  // BD内容卡片
  .build-content-card {
    background-color: $d2r-bg-darker;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .card-title {
      font-size: 16px;
      color: $d2r-gold;
      margin-bottom: 10px;
      display: block;
    }
    
    .build-content {
      font-size: 14px;
      color: $d2r-text;
      line-height: 1.6;
      white-space: pre-wrap;
    }
  }
  
  // 装备卡片
  .build-items-card {
    background-color: $d2r-bg-darker;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .card-title {
      font-size: 16px;
      color: $d2r-gold;
      margin-bottom: 10px;
      display: block;
    }
    
    .items-list {
      display: flex;
      flex-wrap: wrap;
      
      .item-card {
        width: 33.33%;
        padding: 5px;
        margin-bottom: 10px;
        
        .item-image-container {
          width: 60px;
          height: 60px;
          padding: 3px;
          background-color: $d2r-bg-dark;
          border-radius: 4px;
          margin: 0 auto 5px;
          
          .item-image {
            width: 100%;
            height: 100%;
          }
        }
        
        .item-info {
          text-align: center;
          
          .item-name {
            font-size: 12px;
            margin-bottom: 2px;
            display: block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
          
          .item-type {
            font-size: 10px;
            color: $d2r-text-muted;
          }
        }
      }
    }
  }
  
  // 相关BD卡片
  .related-builds-card {
    background-color: $d2r-bg-darker;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 15px;
    
    .card-title {
      font-size: 16px;
      color: $d2r-gold;
      margin-bottom: 10px;
      display: block;
    }
    
    .related-list {
      .related-item {
        padding: 10px 0;
        border-bottom: 1px solid $d2r-border;
        
        &:last-child {
          border-bottom: none;
          padding-bottom: 0;
        }
        
        .related-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 5px;
          
          .related-title {
            font-size: 14px;
            color: $d2r-text;
            font-weight: bold;
          }
        }
        
        .related-author {
          font-size: 12px;
          color: $d2r-text-muted;
        }
      }
    }
  }
  
  // 操作按钮
  .action-buttons {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
    
    .action-button {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      text {
        font-size: 14px;
        color: $d2r-text-muted;
        margin-top: 5px;
      }
    }
  }
}

// 品质文本颜色
.text-normal {
  color: $quality-normal;
}

.text-magic {
  color: $quality-magic;
}

.text-rare {
  color: $quality-rare;
}

.text-set {
  color: $quality-set;
}

.text-unique {
  color: $quality-unique;
}

.text-crafted {
  color: $quality-crafted;
}
</style>